import md5 from "md5";
import SysUserModel from "../../dao/model/system/SysUserModel";
import { IUserModel } from "../../entities/system/SysUserEntity";
import { JWTHelper } from "../../utils/JWTHelper";
import { ServerError, ValidationError } from "../../utils/errors";
import { pick } from "../../utils/tools";
import { decrypt } from "../../utils/jsencrypt";
import { ClientInfo } from "../../routes/system/utils/ClientInfo";
import SysParamsSettingModel from "../../dao/model/system/SysParamsSettingModel";

export interface ILoginBody {
  loginId: string;
  loginPwd: string;
  code: string;
}

export class LoginService {
  public static async login(params: ILoginBody, req: any) {
    const enableCaptcha = await SysParamsSettingModel.findOne({
      where: {
        paramsCode: "enable_captcha",
      },
    });
    // 进入此if证明需要验证验证码
    if (
      +enableCaptcha.dataValues.paramsValue === 1 &&
      req.session.captcha?.toLowerCase() !== params.code?.toLowerCase()
    ) {
      ClientInfo.getClientInfo(req, "0", "验证码错误");
      throw new ValidationError("验证码错误");
    }
    req.session.captcha = "";

    // 根据账号密码查询数据
    params.loginPwd = md5(decrypt(params.loginPwd));
    const data = await SysUserModel.findOne<IUserModel>({
      where: {
        loginId: params.loginId,
        loginPwd: params.loginPwd,
      },
    });

    // 未查出数据证明登录失败
    if (!data) {
      ClientInfo.getClientInfo(req, "0", "账号或密码错误");
      throw new ServerError("账号或密码错误", 500);
    }

    // 验证账号是否被禁用
    if (+data.dataValues.status === 0) {
      ClientInfo.getClientInfo(req, "0", "该账号已被禁用");
      throw new ServerError("该账号已被禁用，如需请联系管理员", 500);
    }

    // 走到这证明登录成功
    ClientInfo.getClientInfo(req, "1", "登录成功");
    const token = JWTHelper.createJwt(pick(data.dataValues, ["id", "loginId", "nickname"]));
    return { token };
  }
}
